"""Load CSV file from old tms program"""
import csv, bz2, cPickle
import wx, datetime
import Tms

def convertDate(strDate, ascii=False):
    """Convert string date to wxDateTime format"""
    if strDate == '':
        newDate = ''
    else:
        Mo,Day,Yr = strDate.split('/')
        if len(Yr)==2:
            Yr = '20' + Yr
        if len(Mo)==1:
            Mo = '0' + Mo
        if len(Day)==1:
            Day = '0' + Day
        if ascii:
            newDate = Yr+Mo+Day
        else:
            newDate = [Yr,Mo,Day]
    return newDate
    
def LoadCSV():    
    studentsCsv = open('Students.csv', 'rt')
    reader = csv.DictReader(studentsCsv)
    students = []
    for row in reader:
        students.append(row)
        
        Students = {}
    for person in students:
        Students[int(person['Student ID'])] = {'LastName': person['Last Name'], 'FirstName': person['First Name'], 'ScreenName': person['Alt Name'], 'Sex': person['Gender'], 'Servant': person['Servant'], 'Active': person['Active'], 'Use For': person['Use For'], 'Use Where': person['Use Where'], 'Use Sourceless': person['Use Sourceless'], 'Email': person['Email Address'], 'Phone': person['Phone #'], 'Remarks': person['Remarks']}
        This = Students[int(person['Student ID'])]
        UseFor = This['Use For'].split(',')
        if This['Use Where'] == 'All Classes':
            This['Main School'] = True
            This['Aux School'] = True
        elif This['Use Where']== 'Aux. Only':
            This['Main School'] = False
            This['Aux School'] = True
        else:
            This['Main School'] = True
            This['Aux School'] = False
        del This['Use Where']
        
        if This['Sex']=='Sister':
            This['Sex']='Female'
            del This['Servant']
            if '2' in UseFor:
                This['Talk 2'] = True
            else:
                This['Talk 2'] = False
            if '3' in UseFor:
                This['Talk 3'] = True
            else:
                This['Talk 3'] = False
            if 'ASST' in UseFor:
                This['Assist'] = True
            else:
                This['Assist'] = False
            
        else:
            This['Sex'] = 'Male'
            if This['Servant']=='Y':
                if 'H' in UseFor:
                    This['Talk H'] = True
                else:
                    This['Talk H'] = False
            if '1' in UseFor:
                This['Talk 1'] = True
            else:
                This['Talk 1'] = False
            if '3' in UseFor:
                This['Talk 3'] = True
            else:
                This['Talk 3'] = False
            if 'Read' in UseFor:
                This['Reader']=True
            else:
                This['Reader']=False
                
        del This['Use For']

        if This.has_key('Servant'):
            if This['Servant']=='Y':
                This['Servant']=True
            else:
                This['Servant']=False
                
        if This['Active']=='Y':
            This['Active']=True
        else:
            This['Active']=False
            
        This['Phone'] = This['Phone'].replace('-','')
        if len(This['Phone']) == 7:
            This['Phone'] = '803' + This['Phone']
        
        This['ScreenName'] = This['LastName'] + ', ' + This['FirstName']
        
    studentsCsv.close()
        
        
    calendarCsv = open('Calendar.csv', 'rt')
    reader = csv.DictReader(calendarCsv)
    calendar = []
    for row in reader:
        calendar.append(row)
    calendarCsv.close()
    
    Calendar = {}
    for week in calendar:
        Calendar[week['Date']] = {'Status':week['Status'], 'Meeting':week['Meeting'], 'CO Visit':week['CO Visit'], 'Review':week['Review'], 'H Source':week['H_Source'], '1 Source':week['1_Source'],'2 Source':week['2_Source'], '2 Theme':week['2_Theme'], '3 Source':week['3_Source'], '3 Theme':week['3_Theme'], '3 Bro Only':week['#3 Brother Only'], 'H ID': week['H_ID'], '1a ID':week['1A_ID'], '2a ID':week['2A_ID'], '2a Assist ID':week['2AASST_ID'], '3a ID':week['3A_ID'], '3a Assist ID':week['3AASST_ID'], '1b ID':week['1B_ID'], '2b ID':week['2B_ID'], '2b Assist ID':week['2BASST_ID'], '3b ID':week['3B_ID'], '3b Assist ID':week['3BASST_ID']}
        
    settingHistoryCsv = open('Setting History.csv', 'rt')
    reader = csv.DictReader(settingHistoryCsv)
    settingHistory = []
    for row in reader:
        settingHistory.append(row)
    settingHistoryCsv.close()
    
    SettingHistory = {}
    for Set in settingHistory:
        if SettingHistory.has_key(Set['Student ID']):
            SettingHistory[int(Set['Student ID'])][int(Set['Setting#'])] = convertDate(Set['Date Used'])
        else:
            SettingHistory[int(Set['Student ID'])] = {int(Set['Setting#']):convertDate(Set['Date Used'])}
    print SettingHistory
    
    studyCsv = open('Study History.csv', 'rt')
    reader = csv.DictReader(studyCsv)
    studyHistory = []
    for row in reader:
        studyHistory.append(row)
    studyCsv.close()
    
    StudyHistory = {}
    for Set in studyHistory:
        item = {'Assigned':convertDate(Set['Date Assigned']), 'Completed':convertDate(Set['Date Completed'])}
        id = int(Set['Student ID'])
        study = int(Set['Study#'])
        if StudyHistory.has_key(id):
            StudyHistory[id][study] = item
##            if StudyHistory[id].has_key(study):
##                StudyHistory[id][study].append(item)
##            else:
##                StudyHistory[id][study] = [item]
        else:
            StudyHistory[id]= {study:item}
    
    talkCsv = open('Talk History.csv', 'rt')
    reader = csv.DictReader(talkCsv)
    talkHistory = []
    for row in reader:
        talkHistory.append(row)
    talkCsv.close()
    
    TalkHistory = {}
    for talk in talkHistory:
        if talk['Study'].isdigit():
            talk['Study']=int(talk['Study'])
        else:
            talk['Study']=0
            
        date = convertDate(talk['Talk Date'])
        if TalkHistory.has_key(int(talk['Student ID'])):
            TalkHistory[int(talk['Student ID'])].append({'Date': date, 'Talk':talk['Talk'], 'Result':talk['Result'], 'Study':talk['Study'], 'Remarks':talk['Remarks']})
        else:
            TalkHistory[int(talk['Student ID'])]= [{'Date':date, 'Talk':talk['Talk'], 'Result':talk['Result'], 'Study':talk['Study'], 'Remarks':talk['Remarks']}]
   
    
    Alldata = [TalkHistory,StudyHistory,SettingHistory,Calendar,Students]
    
    fh = bz2.BZ2File('TMS.Data', 'wb',0,1)
    cPickle.dump(Alldata, fh, cPickle.HIGHEST_PROTOCOL)

if __name__ == '__main__':
    Tms.Main()
    